<?php

/**
 * Subclass for representing a row from the 'gallery' table.
 *
 *
 *
 * @package lib.model
 */
class Gallery extends BaseGallery
{
    /**
     * deletes objets and all children files (photos)
     */
    public function delete($con = null)
    {
        Files::deleteByObjId($this->id, true, MyConstants::TYPE_GALLERY);
        parent::delete($con);
    }
    
    public static function getNewOrUnused($treeId, $userId)
    {
        /* TODO: check for empty galleries */
        $gallery = new Gallery();
        $gallery->setUserId($userId);
        $gallery->setStatusId(MyConstants::STATUS_DELETED);
        return $gallery;
    }
    
    /**
     * Returns list of galleries from Tree, by parent ID or empty array
     *
     * @param integer $parentId
     */
    public static function getByParent($parentId)
    {
        /* @var $tree Tree */
        $ar = array();

        // Selects ID of galleries from `tree`
        $query = sprintf(
            'SELECT %s AS `obj_id` FROM %s LEFT JOIN %s ON( %s = %s ) WHERE %s = %d ORDER BY %s DESC'
            , TreePeer::OBJ_ID
            , TreePeer::TABLE_NAME
            , GalleryPeer::TABLE_NAME
            , TreePeer::OBJ_ID
            , GalleryPeer::ID
            , TreePeer::PARENT_ID
            , $parentId
            , TreePeer::PRIORITY
        );
        
        $con = Propel::getConnection();
        $stmt = $con->prepareStatement($query);
        $rs = $stmt->executeQuery();
        
        // Prepare array of IDs to retrieve from `gallery`
        $arIds = array();
        while( $rs->next() )
        {
            $arIds[$rs->getInt('obj_id')] = $rs->getInt('obj_id');
        }

        return GalleryPeer::retrieveByPKs($arIds);
    }
    
    protected static $m_arFirstPhotos = array();
    public function getFirstPhoto($dirName = 'tiny')
    {
        if( empty(self::$m_arFirstPhotos[$this->id]) )
        {
            $c = new Criteria();
            $c->add(FilesPeer::OBJ_ID, $this->id);
            $c->add(FilesPeer::OBJ_TYPE, MyConstants::TYPE_GALLERY);
            $c->addDescendingOrderByColumn(FilesPeer::PRIORITY);
            
            self::$m_arFirstPhotos[$this->id] = FilesPeer::doSelectOne($c);
            if( empty(self::$m_arFirstPhotos[$this->id]) )
            {
                self::$m_arFirstPhotos[$this->id] = new Files();
            }
        }
        
        return self::$m_arFirstPhotos[$this->id];
    }
    
    /**
     * Faq::hydrate()
     * Sets culture to result set retrieved from database in order not to set it everytime when writing new method
     * @param ResultSet $rs
     * @param integer $startcol
     *
     */
    public function hydrate(ResultSet $rs, $startcol = 1)
    {
        $this->setCulture(sfContext::getInstance()->getUser()->getCulture());
        parent::hydrate($rs, $startcol);
    }
}